package com.zx.sercurity;

import android.content.Context;
import android.util.Log;

import androidx.annotation.IntRange;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步风险控制，实现思路是：
 * 启动一个倒计时，倒计时结束将会触发风控，
 * 在倒计时时间内，满足某些条件将会重置倒计时时间
 */
public abstract class CountDownAsyncRiskControl<T> extends AsyncRiskControlAbs<T> {

    private static final String TAG = "CountDownRiskControl";

    private final long TIME_THRESHOLD = riskHolderTime();

    public CountDownAsyncRiskControl(AsyncRiskListener listener) {
        super(listener);
    }

    @IntRange(from = 1)
    protected abstract long riskHolderTime();

    public void beginCheck(Context context) {
        Log.i(TAG, "BeginCheck");
        boolean startUp = startUp(context);
        if (startUp) {
            resetCountdown();
        }else {
            startUpCanceled();
        }
    }

    protected abstract boolean startUp(Context context);

    protected abstract void startUpCanceled();

    protected abstract Runnable onCountDownTrigger();

    protected void resetCountdown() {
        ScheduledExecutorService execService = getService();
        if (execService.isShutdown()) {
            Log.i(TAG, "Service is shutdown, skip countdown.");
            return;
        }

        if (schedule != null && !schedule.isCancelled()) {
            schedule.cancel(true);
        }

        Log.i(TAG, "Resetting countdown for: " + this.getClass().getSimpleName());
        schedule = execService.schedule(onCountDownTrigger(), TIME_THRESHOLD, TimeUnit.MILLISECONDS);
    }

    protected void stopCountdown() {
        Log.i(TAG, "Stopping countdown for: " + this.getClass().getSimpleName());
        if (schedule != null && !schedule.isCancelled()) {
            schedule.cancel(true);
            schedule = null;
        }
    }
}

